package com.base.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.base.conf.RedisHelper;
import com.base.controller.BaseController;
import com.base.service.AsyncLogRecord;
import com.base.utils.CookieUtil;
import com.base.vo.LoginUserInfo;

/**
 * @类描述：操作日志记录
 * @创建人：wangdw
 * @创建时间：2018年11月6日 下午1:32:11
 */
@Component
public class LogRecordInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private AsyncLogRecord asyncLogRecordHandle;
    
    @Autowired
    private RedisHelper redisHelper;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取用户信息(异步方法在生产环境不能获取到用户cookie)
        String token = CookieUtil.getCookie(request, BaseController.TOKEN_COOKIE_NAME);
        LoginUserInfo userInfo = new LoginUserInfo();// (LoginUserInfo)
                                                     // redisHelper.get(BaseController.USER_KEY +
                                                     // token);
        if (userInfo == null) {
            logger.info("未获取到用户信息，不记录操作日志！token:{}", token);
            return true;
        }
        this.asyncLogRecordHandle.save(request, handler, userInfo);
        
        return true;
    }
    
}
